import random

from qcloudsms_py import SmsSingleSender


from .settings import *
from utils.logging import get_logger


logger = get_logger()


def get_code():
    code = ''
    for i in range(4):
        code += str(random.randint(0, 9))
    return code


def send_code(mobile, code):
    sender = SmsSingleSender(appid, appkey)
    params = [code, 5]
    try:
        result = sender.send_with_param(
            86, mobile,
            template_id,
            params,
            sign=sms_sign,
            extend="",
            ext=""
        )
    except Exception as e:
        # 记录日志
        logger.error('%s手机号，发送短信失败，错误信息是%s' % (mobile, str(e)))
    if result['result'] == 0:
        return True
    else:
        logger.warning('%s手机号，发送短信失败,失败原因是%s' % (mobile, result['errmsg']))
        return False


if __name__ == '__main__':
    print(get_code())
